/**
 * @file 数据绑定示例组件
 * 
 * 展示低代码平台中的数据绑定功能
 */
import React, { useState, useEffect } from 'react';
import dataSourceRegistry from '../data/DataSourceRegistry.jsx';

/**
 * 数据绑定示例组件
 */
const DataBindingExample = () => {
  const [userInfo, setUserInfo] = useState(null);
  const [productInfo, setProductInfo] = useState(null);
  const [orderInfo, setOrderInfo] = useState(null);
  const [inputValues, setInputValues] = useState({
    userName: '',
    userAge: '',
    productName: '',
    productPrice: '',
    quantity: 1
  });

  // 组件加载时初始化数据源
  useEffect(() => {
    initDataSources();
    setupBindings();
    
    return () => {
      // 清理绑定和数据源
      clearBindings();
    };
  }, []);

  // 初始化数据源
  const initDataSources = () => {
    // 清除可能存在的旧数据源
    try {
      ['userDataSource', 'productDataSource', 'orderDataSource'].forEach(id => {
        if (dataSourceRegistry.getDataSource(id)) {
          dataSourceRegistry.removeDataSource(id);
        }
      });
    } catch (err) {
      console.warn('清除旧数据源出错', err);
    }

    // 创建用户数据源
    dataSourceRegistry.registerDataSource({
      id: 'userDataSource',
      name: '用户数据',
      type: 'static',
      options: {
        data: {
          name: '张三',
          age: 30,
          isVip: true,
          registerDate: '2023-01-15'
        }
      }
    });

    // 创建产品数据源
    dataSourceRegistry.registerDataSource({
      id: 'productDataSource',
      name: '产品数据',
      type: 'static',
      options: {
        data: {
          name: '低代码平台专业版',
          price: 199,
          description: '专业的低代码开发平台',
          inStock: true
        }
      }
    });

    // 创建订单数据源(计算型)
    dataSourceRegistry.registerDataSource({
      id: 'orderDataSource',
      name: '订单数据',
      type: 'computed',
      options: {
        expression: `
          ({
            userName: userDataSource.name,
            productName: productDataSource.name,
            unitPrice: productDataSource.price,
            quantity: 1,
            totalPrice: productDataSource.price * 1,
            discount: userDataSource.isVip ? 0.9 : 1,
            finalPrice: productDataSource.price * 1 * (userDataSource.isVip ? 0.9 : 1),
            orderDate: new Date().toLocaleDateString()
          })
        `,
        dependencies: ['userDataSource', 'productDataSource']
      }
    });

    // 加载数据源数据
    loadDataSources();
  };

  // 加载数据源
  const loadDataSources = async () => {
    try {
      const userDataSource = dataSourceRegistry.getDataSource('userDataSource');
      if (userDataSource) {
        const userData = await userDataSource.load();
        setUserInfo(userData);
        
        // 同步到表单
        setInputValues(prev => ({
          ...prev,
          userName: userData.name,
          userAge: userData.age
        }));
      }

      const productDataSource = dataSourceRegistry.getDataSource('productDataSource');
      if (productDataSource) {
        const productData = await productDataSource.load();
        setProductInfo(productData);
        
        // 同步到表单
        setInputValues(prev => ({
          ...prev,
          productName: productData.name,
          productPrice: productData.price
        }));
      }

      const orderDataSource = dataSourceRegistry.getDataSource('orderDataSource');
      if (orderDataSource) {
        const orderData = await orderDataSource.load(dataSourceRegistry);
        setOrderInfo(orderData);
        
        // 同步到表单
        setInputValues(prev => ({
          ...prev,
          quantity: orderData.quantity
        }));
      }
    } catch (err) {
      console.error('加载数据源出错', err);
    }
  };

  // 设置数据绑定
  const setupBindings = () => {
    // 设置组件更新回调
    dataSourceRegistry.setComponentUpdateCallback(
      'orderForm', 
      'quantity',
      (newValue) => {
        setInputValues(prev => ({
          ...prev,
          quantity: Number(newValue) || 1
        }));
        
        // 更新订单数据源
        const orderDataSource = dataSourceRegistry.getDataSource('orderDataSource');
        if (orderDataSource) {
          // 更新表达式
          if (typeof orderDataSource.updateExpression === 'function') {
            orderDataSource.updateExpression(`
              ({
                userName: userDataSource.name,
                productName: productDataSource.name,
                unitPrice: productDataSource.price,
                quantity: ${Number(newValue) || 1},
                totalPrice: productDataSource.price * ${Number(newValue) || 1},
                discount: userDataSource.isVip ? 0.9 : 1,
                finalPrice: productDataSource.price * ${Number(newValue) || 1} * (userDataSource.isVip ? 0.9 : 1),
                orderDate: new Date().toLocaleDateString()
              })
            `);
          }
          
          // 重新加载
          orderDataSource.load(dataSourceRegistry).then(data => {
            setOrderInfo(data);
          });
        }
      }
    );
  };

  // 清理数据绑定
  const clearBindings = () => {
    dataSourceRegistry.removeComponentUpdateCallback('orderForm', 'quantity');
    
    // 清除数据源
    ['userDataSource', 'productDataSource', 'orderDataSource'].forEach(id => {
      if (dataSourceRegistry.getDataSource(id)) {
        dataSourceRegistry.removeDataSource(id);
      }
    });
  };

  // 处理输入变化
  const handleInputChange = (field, value) => {
    setInputValues(prev => ({
      ...prev,
      [field]: value
    }));

    // 根据字段更新对应的数据源
    if (field === 'userName' || field === 'userAge') {
      const userDataSource = dataSourceRegistry.getDataSource('userDataSource');
      if (userDataSource) {
        const userData = userDataSource.getData() || {};
        const newData = { 
          ...userData,
          [field === 'userName' ? 'name' : 'age']: field === 'userAge' ? Number(value) : value
        };
        
        userDataSource.updateData(newData);
        setUserInfo(newData);
      }
    } else if (field === 'productName' || field === 'productPrice') {
      const productDataSource = dataSourceRegistry.getDataSource('productDataSource');
      if (productDataSource) {
        const productData = productDataSource.getData() || {};
        const newData = { 
          ...productData,
          [field === 'productName' ? 'name' : 'price']: field === 'productPrice' ? Number(value) : value
        };
        
        productDataSource.updateData(newData);
        setProductInfo(newData);
      }
    } else if (field === 'quantity') {
      // 调用之前设置的组件更新回调
      dataSourceRegistry.handleComponentPropChange('orderForm', 'quantity', value);
    }
  };

  return (
    <div style={{ maxWidth: '900px', margin: '0 auto', padding: '20px' }}>
      <h2>数据绑定示例</h2>
      
      <p>本示例展示了低代码平台中的数据绑定功能，包括表单与数据源的双向绑定。</p>
      
      <div style={{ 
        display: 'grid', 
        gridTemplateColumns: '1fr 1fr', 
        gap: '20px',
        marginTop: '20px'
      }}>
        {/* 左侧表单 */}
        <div>
          <div style={{ 
            border: '1px solid #e8e8e8', 
            borderRadius: '4px',
            padding: '16px'
          }}>
            <h3 style={{ marginTop: 0 }}>编辑数据</h3>
            
            {/* 用户信息 */}
            <fieldset style={{ marginBottom: '16px', border: '1px solid #d9d9d9', borderRadius: '4px', padding: '12px' }}>
              <legend>用户信息</legend>
              
              <div style={{ marginBottom: '12px' }}>
                <label style={{ display: 'block', marginBottom: '4px' }}>姓名:</label>
                <input 
                  type="text"
                  value={inputValues.userName || ''}
                  onChange={(e) => handleInputChange('userName', e.target.value)}
                  style={{ 
                    width: '100%', 
                    padding: '8px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '2px'
                  }}
                />
              </div>
              
              <div style={{ marginBottom: '12px' }}>
                <label style={{ display: 'block', marginBottom: '4px' }}>年龄:</label>
                <input 
                  type="number"
                  value={inputValues.userAge || ''}
                  onChange={(e) => handleInputChange('userAge', e.target.value)}
                  style={{ 
                    width: '100%', 
                    padding: '8px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '2px'
                  }}
                />
              </div>
            </fieldset>
            
            {/* 产品信息 */}
            <fieldset style={{ marginBottom: '16px', border: '1px solid #d9d9d9', borderRadius: '4px', padding: '12px' }}>
              <legend>产品信息</legend>
              
              <div style={{ marginBottom: '12px' }}>
                <label style={{ display: 'block', marginBottom: '4px' }}>产品名称:</label>
                <input 
                  type="text"
                  value={inputValues.productName || ''}
                  onChange={(e) => handleInputChange('productName', e.target.value)}
                  style={{ 
                    width: '100%', 
                    padding: '8px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '2px'
                  }}
                />
              </div>
              
              <div style={{ marginBottom: '12px' }}>
                <label style={{ display: 'block', marginBottom: '4px' }}>产品价格:</label>
                <input 
                  type="number"
                  value={inputValues.productPrice || ''}
                  onChange={(e) => handleInputChange('productPrice', e.target.value)}
                  style={{ 
                    width: '100%', 
                    padding: '8px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '2px'
                  }}
                />
              </div>
            </fieldset>
            
            {/* 订单信息 */}
            <fieldset style={{ border: '1px solid #d9d9d9', borderRadius: '4px', padding: '12px' }}>
              <legend>订单信息</legend>
              
              <div style={{ marginBottom: '12px' }}>
                <label style={{ display: 'block', marginBottom: '4px' }}>购买数量:</label>
                <input 
                  type="number"
                  min="1"
                  value={inputValues.quantity || 1}
                  onChange={(e) => handleInputChange('quantity', e.target.value)}
                  style={{ 
                    width: '100%', 
                    padding: '8px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '2px'
                  }}
                />
              </div>
            </fieldset>
          </div>
        </div>
        
        {/* 右侧数据展示 */}
        <div>
          <div style={{ 
            border: '1px solid #e8e8e8', 
            borderRadius: '4px',
            padding: '16px',
            height: '100%'
          }}>
            <h3 style={{ marginTop: 0 }}>数据源内容</h3>
            
            <div style={{ marginBottom: '16px' }}>
              <h4 style={{ margin: '0 0 8px 0' }}>用户数据源:</h4>
              <pre style={{ 
                backgroundColor: '#f5f5f5',
                padding: '8px',
                borderRadius: '4px',
                maxHeight: '120px',
                overflow: 'auto',
                margin: 0
              }}>
                {JSON.stringify(userInfo, null, 2)}
              </pre>
            </div>
            
            <div style={{ marginBottom: '16px' }}>
              <h4 style={{ margin: '0 0 8px 0' }}>产品数据源:</h4>
              <pre style={{ 
                backgroundColor: '#f5f5f5',
                padding: '8px',
                borderRadius: '4px',
                maxHeight: '120px',
                overflow: 'auto',
                margin: 0
              }}>
                {JSON.stringify(productInfo, null, 2)}
              </pre>
            </div>
            
            <div>
              <h4 style={{ margin: '0 0 8px 0' }}>订单数据源 (计算):</h4>
              <pre style={{ 
                backgroundColor: '#f5f5f5',
                padding: '8px',
                borderRadius: '4px',
                maxHeight: '150px',
                overflow: 'auto',
                margin: 0
              }}>
                {JSON.stringify(orderInfo, null, 2)}
              </pre>
            </div>
          </div>
        </div>
      </div>
      
      <div style={{ 
        marginTop: '30px', 
        padding: '15px', 
        backgroundColor: '#e6f7ff', 
        borderRadius: '4px' 
      }}>
        <h3 style={{ marginTop: 0 }}>数据绑定说明</h3>
        <ul>
          <li>数据在表单和数据源之间实现了双向绑定</li>
          <li>订单数据源是一个计算型数据源，依赖于用户和产品数据源</li>
          <li>当表单中的值变化时，会自动更新对应的数据源</li>
          <li>当数据源更新时，会触发计算型数据源的重新计算</li>
        </ul>
      </div>
    </div>
  );
};

export default DataBindingExample; 